<template>
  <div class="user-management">
    <div class="page-header">
      <h2>{{ pageTitle }}</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        {{ addButtonText }}
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 用户表格 -->
    <el-card>
      <el-table :data="userList" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.role === '管理员' ? 'danger' : 'primary'">
              {{ scope.row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

export default {
  name: 'UserManagement',
  components: {
    Plus
  },
  setup() {
    const route = useRoute()
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const userFormRef = ref()
    
    // 动态标题 - 根据查询参数确定页面标题
    const pageTitle = computed(() => {
      if (route.query.title) {
        return route.query.title
      }
      return '用户管理'
    })
    
    // 动态按钮文字
    const addButtonText = computed(() => {
      if (route.query.title === '我的客户') {
        return '添加客户'
      }
      return '新增用户'
    })
    
    const searchForm = reactive({
      username: '',
      email: '',
      status: ''
    })
    
    const userForm = reactive({
      id: null,
      username: '',
      email: '',
      phone: '',
      role: '',
      status: 1
    })
    
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }
    
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 原始数据
    const allUserList = ref([
      {
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        phone: '13800138000',
        role: '管理员',
        status: 1,
        createTime: '2025-07-10 10:00:00'
      },
      {
        id: 2,
        username: 'user1',
        email: 'user1@example.com',
        phone: '13800138001',
        role: '普通用户',
        status: 1,
        createTime: '2025-07-10 11:00:00'
      },
      {
        id: 3,
        username: 'user2',
        email: 'user2@example.com',
        phone: '13800138002',
        role: '普通用户',
        status: 0,
        createTime: '2025-07-10 12:00:00'
      }
    ])
    // 当前展示数据
    const userList = ref([])
    
    // 搜索
    // 搜索和筛选功能
    const filterUserList = () => {
      let filtered = allUserList.value.slice()
      // 用户名模糊和首字母匹配
      if (searchForm.username) {
        const keyword = searchForm.username.trim().toLowerCase()
        filtered = filtered.filter(item => {
          const name = item.username.toLowerCase()
          return name.includes(keyword) || name[0] === keyword
        })
      }
      // 邮箱模糊匹配
      if (searchForm.email) {
        const keyword = searchForm.email.trim().toLowerCase()
        filtered = filtered.filter(item => item.email.toLowerCase().includes(keyword))
      }
      // 状态筛选
      if (searchForm.status !== '' && searchForm.status !== null) {
        filtered = filtered.filter(item => String(item.status) === String(searchForm.status))
      }
      pagination.total = filtered.length
      // 分页
      const startIdx = (pagination.currentPage - 1) * pagination.pageSize
      const endIdx = startIdx + pagination.pageSize
      userList.value = filtered.slice(startIdx, endIdx)
    }

    const handleSearch = () => {
      pagination.currentPage = 1
      filterUserList()
    }

    const handleReset = () => {
      Object.assign(searchForm, {
        username: '',
        email: '',
        status: ''
      })
      pagination.currentPage = 1
      filterUserList()
    }
    
    // 新增
    const handleAdd = () => {
      dialogTitle.value = '新增用户'
      dialogVisible.value = true
      Object.assign(userForm, {
        id: null,
        username: '',
        email: '',
        phone: '',
        role: '',
        status: 1
      })
    }
    
    // 编辑
    const handleEdit = (row) => {
      dialogTitle.value = '编辑用户'
      dialogVisible.value = true
      Object.assign(userForm, { ...row })
    }
    
    // 删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除用户 ${row.username} 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const index = allUserList.value.findIndex(item => item.id === row.id)
        if (index > -1) {
          allUserList.value.splice(index, 1)
          filterUserList()
          ElMessage.success('删除成功')
        }
      })
    }
    
    // 状态切换
    const handleStatusChange = (row) => {
      const index = allUserList.value.findIndex(item => item.id === row.id)
      if (index > -1) {
        allUserList.value[index].status = row.status
        filterUserList()
      }
      ElMessage.success(`${row.username} 状态已更新`)
    }
    
    // 分页大小改变
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      pagination.currentPage = 1
      filterUserList()
    }

    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      filterUserList()
    }
    
    // 提交表单
    const handleSubmit = () => {
      userFormRef.value.validate((valid) => {
        if (valid) {
          if (userForm.id) {
            // 编辑
            const index = allUserList.value.findIndex(item => item.id === userForm.id)
            if (index > -1) {
              allUserList.value[index] = { ...userForm }
              filterUserList()
              ElMessage.success('编辑成功')
            }
          } else {
            // 新增
            const newUser = {
              ...userForm,
              id: Date.now(),
              createTime: new Date().toLocaleString()
            }
            allUserList.value.unshift(newUser)
            filterUserList()
            ElMessage.success('新增成功')
          }
          dialogVisible.value = false
        }
      })
    }
    
    // 对话框关闭
    const handleDialogClose = () => {
      userFormRef.value?.resetFields()
    }
    
    onMounted(() => {
      filterUserList()
    })
    
    return {
      pageTitle,
      addButtonText,
      loading,
      dialogVisible,
      dialogTitle,
      userFormRef,
      searchForm,
      userForm,
      userRules,
      pagination,
      userList,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleDelete,
      handleStatusChange,
      handleSizeChange,
      handleCurrentChange,
      handleSubmit,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
